package com.aoxiang.zbox.config;

import com.aoxiang.zbox.common.DynamicDataSource;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

@Configuration
public class DataSourceConfig {
    public static final String BASE_DATASOURCE_KEY = "base";
    private static final String DB_FOLDER = "databases/";

    public static String getUserDatabasePath(Long userId) {
        return DB_FOLDER + "user_" + userId + ".db";
    }

    public static String getUserDatabaseKey(Long userId) {
        return "user_" + userId;
    }

    public static String generateDbUrl(String dataSourceKey) {
        if (DataSourceConfig.BASE_DATASOURCE_KEY.equals(dataSourceKey)) {
            return "jdbc:sqlite:databases/base.db"; // 基础数据库
        }
        return "jdbc:sqlite:databases/" + dataSourceKey + ".db"; // 用户数据库
    }

    @Bean
    @Primary
    public DataSource dataSource() {
        DynamicDataSource dynamicDataSource = new DynamicDataSource();

        // 配置基础数据源
        DataSource baseDataSource = DataSourceBuilder.create()
                .driverClassName("org.sqlite.JDBC")
                .url("jdbc:sqlite:databases/base.db") // 配置基础数据源的 URL
                .build();

        Map<Object, Object> dataSourceMap = new HashMap<>();
        dataSourceMap.put("base", baseDataSource);

        dynamicDataSource.setTargetDataSources(dataSourceMap);
        dynamicDataSource.setDefaultTargetDataSource(baseDataSource);

        return dynamicDataSource;
    }

    @Bean
    public PlatformTransactionManager transactionManager(DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }
}
